package com.example.zhidao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhidao.model.po.Admin;
import com.example.zhidao.model.po.User;
import com.example.zhidao.model.responseData.ResponseData;
import com.example.zhidao.service.AdminService;
import com.example.zhidao.utils.Ujwt;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {//6


    @Autowired
    private AdminService adminService;

    @Autowired
    private Ujwt ujwt;


//    管理员登录界面
    @GetMapping("/login")
    public ResponseData adminlogin(String name,String password){

        if(name==null || password==null){
            return new ResponseData(null,false,"输入的账号或密码为空",203);
        }else{
            QueryWrapper<Admin> qw=new QueryWrapper<>();
            qw.eq("name",name);
            qw.eq("password",password);

            Admin admin=adminService.getOne(qw);

            if(admin==null){
                return new ResponseData(null,false,"该用户不存在",202);
            }else{
                String token=ujwt.gettoken1(admin);//对从user中的id name两个字段进行加密，并设置时间进行7天免密登录
                System.out.println(token);
                UpdateWrapper<Admin> uw=new UpdateWrapper<>();
                uw.eq("id",admin.getId());
                uw.set("token",token);
                boolean i=adminService.update(uw);

                Map<String, String> keyValueMap = new HashMap<>();
                keyValueMap.put("token",token);
                keyValueMap.put("auth",admin.getAuth()+"");
                if(i){
                    return new ResponseData(keyValueMap,true,"登录成功，返回token",200);
                }else{
                    return new ResponseData(null,false,"登录失败",201);
                }
            }
        }
    }


//    管理员信息
@GetMapping("/info")
public ResponseData adminlogin(@RequestHeader String token){
    Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
    String aid=claims.getId();
    QueryWrapper<Admin> q=new QueryWrapper();
    q.eq("id",aid);
    Admin admin=adminService.getOne(q);
    if(admin==null){
        return new ResponseData(null,false,"你不是管理员",300);
    }
    return new ResponseData(admin,false,"成功获取信息",200);
}



//以下为boss的权限

//获取员工列表
@GetMapping("/list")
public ResponseData adminList(@RequestHeader String token,String id,String name, Page page){
    Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
    String aid=claims.getId();
    QueryWrapper<Admin> q=new QueryWrapper();
    q.eq("id",aid);
    Admin a=adminService.getOne(q);
    if(a==null){
        return new ResponseData(null,false,"你不是管理员",300);
    }
    if(a.getAuth()!=0){
        return new ResponseData(null,false,"你不是Boss",400);
    }

    QueryWrapper<Admin> qw=new QueryWrapper();
    qw.like(name!="","name",name);
    qw.like(id!="","id",id);
    qw.orderByAsc("auth");

    Page<Admin> p=adminService.page(page,qw);

    if(p!=null){
        return new ResponseData(p,false,"成功获取信息",200);
    }else{
        return new ResponseData(null,false,"信息获取失败",201);
    }


}




    //创建员工
    @PostMapping ("/add")
    public ResponseData addAdmin(Admin admin,@RequestParam(value = "token") String token, MultipartFile upload) {
        Claims claims = (Claims) ujwt.tokenToOut(token);//强制转换属性
        String aid = claims.getId();
        QueryWrapper<Admin> q = new QueryWrapper();
        q.eq("id", aid);
        Admin a = adminService.getOne(q);
        if (a == null) {
            return new ResponseData(null, false, "你不是管理员", 300);
        }
        if (a.getAuth() != 0) {
            return new ResponseData(null, false, "你不是Boss", 400);
        }


        String fileName = upload.getOriginalFilename();
        admin.setImg(fileName);
//        String path = "F:/202202/upload1/";
         String path = "/home/ubuntu/blog/upload/"; //阿里云
        File file = new File(path); //3. 判断路径是否存在，不存在则新建
        if (!file.exists()){
            file.mkdir();
        }
        // 3.改名,避免重名,定义新文件的名字
        // String newName = path+File.separator+System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
        String message="图片上传失败";
        try {
            upload.transferTo(new File(path+fileName));
            message= "上传成功";
        } catch (IOException e) {
            message=message+e.toString();
            return new ResponseData(-1, false, message, 201);
        }

        QueryWrapper<Admin> qw = new QueryWrapper();
        qw.eq("name",admin.getName()).eq("password",admin.getPassword());
        if(adminService.getOne(qw)!=null){
            return new ResponseData(null, false, "密码或用户名已存在", 203);
        }


        Date date=new Date();

        admin.setCreatetime(date);
        admin.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        admin.setToken(null);
        boolean i=adminService.save(admin);

        if(i){
            return new ResponseData(i, true, "添加成功", 200);
        }else{
            return new ResponseData(null, false, "添加失败", 202);
        }
    }


//    删除员工
    @DeleteMapping("/del")
    public ResponseData deladmin(@RequestHeader String token,String id){
        Claims claims = (Claims) ujwt.tokenToOut(token);//强制转换属性
        String aid = claims.getId();
        QueryWrapper<Admin> q = new QueryWrapper();
        q.eq("id", aid);
        Admin a = adminService.getOne(q);
        if (a == null) {
            return new ResponseData(null, false, "你不是管理员", 300);
        }
        if (a.getAuth() != 0) {
            return new ResponseData(null, false, "你不是Boss", 400);
        }

        boolean i=adminService.removeById(id);

        if(i){
            return new ResponseData(i, true, "成功删除", 200);
        }else{
            return new ResponseData(null, false, "删除失败", 401);
        }
    }


    //修改员工
    @PostMapping ("/update")
    public ResponseData updateAdmin(Admin admin,@RequestParam(value = "token") String token, MultipartFile upload) {
        Claims claims = (Claims) ujwt.tokenToOut(token);//强制转换属性
        String aid = claims.getId();
        QueryWrapper<Admin> q = new QueryWrapper();
        q.eq("id", aid);
        Admin a = adminService.getOne(q);
        if (a == null) {
            return new ResponseData(null, false, "你不是管理员", 300);
        }
        if (a.getAuth() != 0) {
            return new ResponseData(null, false, "你不是Boss", 400);
        }


        String fileName = upload.getOriginalFilename();
        admin.setImg(fileName);
//        String path = "F:/202202/upload1/";
         String path = "/home/ubuntu/blog/upload/"; //阿里云
        File file = new File(path); //3. 判断路径是否存在，不存在则新建
        if (!file.exists()){
            file.mkdir();
        }
        // 3.改名,避免重名,定义新文件的名字
        // String newName = path+File.separator+System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
        String message="图片上传失败";
        try {
            upload.transferTo(new File(path+fileName));
            message= "上传成功";
        } catch (IOException e) {
            message=message+e.toString();
            return new ResponseData(-1, false, message, 201);
        }




        Date date=new Date();


        admin.setToken(null);
        boolean i=adminService.updateById(admin);

        if(i){
            return new ResponseData(i, true, "修改成功", 200);
        }else{
            return new ResponseData(null, false, "修改失败", 202);
        }
    }
}
